package com.dminvoicemanager;

/*Invoice details screen related calculations and functions*/
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.TextView;
import android.widget.Toast;

public class DM_InvoiceDetails extends Activity {
	// private PBDatabaseAdapter dbHelper;
	private String DBNAME = "dminvoicemanager.db";
	// Master Tables
	int pos = 0;
	private String TEMP_USER = "invtempuser";
	private String ITEM_AREA = "fArea";
	private String ITEM_COMPANY_SETTING = "fCompanySetting";
	private String ITEM_CONTROL = "fControl";
	private String ITEM_DEBTOR = "fDebtor";
	private String ITEM_LOC_DETAILS = "fItemLoc";
	private String ITEM_LOCATION = "fLocation";
	private String ITEM_PRICE = "fItemPri";
	private String ITEMS = "fItems";
	private String INV_COMPANY_BRANCH = "FCompanyBranch";
	private String INV_SAL_REP = "fSalRep";

	// Main Invoice
	private String TEMP_REP_INVOICESUMERY = "frepInvoiceSumery";
	private String INV_DETAILS = "FinvDet";
	private String INV_HEADER = "FinvHed";

	// Stock Loading
	private String TEMP_STOCK_LOADING_SUMMARY = "frepStockLoadingSummary";
	private String STOCK_LOAD_HEAD = "fLoadhed";
	private String STOCK_LOAD_DETAIL = "fLoadDet";
	private SQLiteDatabase mydb;
	EditText etdminvditem, TextTransType;
	EditText etdminvdunitval, etdminvdpriceval, etdminvdpricevalunit,
			etdminvdcasesval, etdminvdpiecesval, etdminvddiscountval,
			etdminvdtotitemsval;
	EditText etIvoiveTotDiscount, etTotInvoiceValue;
	String strTypePrint;
	String strType;
	double ItemsPerCase = 0.0;
	double ItemsPrice = 0.0;
	double ItemsCaseTotValue = 0.0;
	double NoOfCasesPerItem = 0.0;
	double NoOfPiecesPerItem = 0.0;
	double ItemsDiscountValue = 0.0;
	double TotValForCases = 0.0;
	double TotValForPieces = 0.0;
	double FinalTotValPerItem = 0.0;
	double InvTotItemQTY = 0.0;
	double TotInvoiceAmount = 0.0;
	double TotInvoiceReturnAmount = 0.0;
	double TotInvoiceDiscountAmount = 0.0;
	double NoOfItemsPerInvoice = 0.0;
	Button InvHeader, InvSelectNewItem, InvAddNewItem, InvDeleteItem,
			InvUpdateItem, spinnerdmtranstypeButton;
	private Spinner SpTransType;
	String invitemcode, Print_Totvalperitem, itemSummeryRawId,
			currentInvoiceTempNo, currentInvoiceTempRefCode,
			LatestInvNumberStr;
	LinearLayout ListAllItems, ListInvItemDetails, ListInvItemDetailsSummery;
	String currentSerial = "1";
	int currentOption, invDetLastSequence = 1;
	String PreTot, TagId, strlastId;
	String invDetLastRefNo = "0", currentUser, currentStOrdNo = "0";
	long lastId;
	int DELTAG = 77, ChkType = 0, CheckAdd = 0;

	// Print Account Description
	@SuppressWarnings("deprecation")
	public void AddItemsDetails(View view) {
		Button des = (Button) view;
		String ItemsRawResult = des.getText().toString();
		String[] accountdetail = ItemsRawResult.split("/");
		String invitemskucode = accountdetail[0]; // invitemskucode
		invitemcode = accountdetail[1]; // invitemcode
		String invitemname = accountdetail[2]; // invitemname
		String invitemsincase = accountdetail[3]; // invitemsincase

		// Check Previously item Enter or Not
		SQLiteDatabase mydb = openOrCreateDatabase(DBNAME,
				Context.MODE_PRIVATE, null);
		Cursor chkItemLocated = null;

		try {
			chkItemLocated = mydb.query(INV_DETAILS, null, "Itemcode='"
					+ invitemcode + "' AND refInvoiceDetNo='"
					+ LatestInvNumberStr + "'", null, null, null, null);
		} catch (Exception e1) {
		}

		if (chkItemLocated != null) {
			if (chkItemLocated.getCount() > 0) {
				while (chkItemLocated.moveToNext()) {
					String previousItemType = chkItemLocated.getString(3);
					String currentItemType = TextTransType.getText().toString();
					if (previousItemType.equalsIgnoreCase(currentItemType)) {
						final AlertDialog alertDialog = new AlertDialog.Builder(
								DM_InvoiceDetails.this).create();
						// Setting Dialog Title
						alertDialog.setTitle("ADD NEW ITEM");
						// Setting Dialog Message
						alertDialog.setMessage("Item Already Entered");
						// Setting Icon to Dialog
						alertDialog.setIcon(R.drawable.warning);
						// Setting OK Button
						alertDialog.setButton("OK",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int which) {
										alertDialog.dismiss();
									}
								});
						// Showing Alert Message
						alertDialog.show();

						ListAllItems.setVisibility(view.VISIBLE);
						ListInvItemDetails.setVisibility(view.GONE);
					} else {

						etdminvditem.setText(invitemname);
						etdminvdunitval.setText(invitemsincase);
						etdminvdpriceval.setText("");
						etdminvdpricevalunit.setText("");
						etdminvdcasesval.setText("");
						etdminvdpiecesval.setText("");
						etdminvddiscountval.setText("");
						etdminvdtotitemsval.setText("");
						setItemsPrice();
						ListAllItems.setVisibility(view.GONE);
						ListInvItemDetails.setVisibility(view.VISIBLE);
					}

				}
			} else {
				etdminvditem.setText(invitemname);
				etdminvdunitval.setText(invitemsincase);
				etdminvdpriceval.setText("");
				etdminvdpricevalunit.setText("");
				etdminvdcasesval.setText("");
				etdminvdpiecesval.setText("");
				etdminvddiscountval.setText("");
				etdminvdtotitemsval.setText("");

				ListAllItems.setVisibility(view.GONE);
				ListInvItemDetails.setVisibility(view.VISIBLE);
				setItemsPrice();
			}
		} else {
			etdminvditem.setText(invitemname);
			etdminvdunitval.setText(invitemsincase);
			etdminvdpriceval.setText("");
			etdminvdpricevalunit.setText("");
			etdminvdpiecesval.setText("");
			etdminvdtotitemsval.setText("");

			ListAllItems.setVisibility(view.GONE);
			ListInvItemDetails.setVisibility(view.VISIBLE);
			setItemsPrice();
		}
		chkItemLocated.close();
		mydb.close();

	}

	// Back to Invoice header without selecting Customer
	public void btnItemsListBack(View view) {
		ListAllItems.setVisibility(view.GONE);
		ListInvItemDetails.setVisibility(view.VISIBLE);
	}

	public void btnShowSpinnerBack(View view) {
		SpTransType.setVisibility(view.VISIBLE);
		spinnerdmtranstypeButton.setVisibility(view.GONE);
	}

	// Show add items details Summery
	public void ShowItemsDetails(View view) {
		Button desSummery = (Button) view;
		String ItemsRawSummeryResult = desSummery.getText().toString();
		String[] accountdetail = ItemsRawSummeryResult.split("/");
		itemSummeryRawId = accountdetail[0]; // Selected raw reference
												// number(using to view record
												// and update raw items in
												// invoices)
		ViewItemListRawSummery();
	}

	private void ViewItemListRawSummery() {
		InvUpdateItem.setEnabled(true);
		InvDeleteItem.setEnabled(true);
		InvAddNewItem.setEnabled(false);
		// TODO Auto-generated method stub
		SQLiteDatabase mydb = openOrCreateDatabase(DBNAME,
				Context.MODE_PRIVATE, null);
		String[] colsInvDet = { "invdet_id" };
		Cursor chkItemListRaw = null;

		try {
			chkItemListRaw = mydb.query(INV_DETAILS, null, null, null, null,
					null, null);
		} catch (Exception e1) {
		}
		if (chkItemListRaw != null) {
			if (chkItemListRaw.getCount() > 0) {

				while (chkItemListRaw.moveToNext()) {
					String itemRefNo = chkItemListRaw.getString(0);
					String itemRefDate = chkItemListRaw.getString(2);
					String itemCodeLoged = chkItemListRaw.getString(5);
					String itemPriceloged = chkItemListRaw.getString(7);
					String itemCasesloged = chkItemListRaw.getString(12);
					String itemTransType = chkItemListRaw.getString(3);
					String itemPiecesloged = chkItemListRaw.getString(14);
					String itemDiscount = chkItemListRaw.getString(18);
					String itemTotInvAmount = chkItemListRaw.getString(22);
					String itemDescription = chkItemListRaw.getString(27);
					String itemCaseQty = chkItemListRaw.getString(30);
					/*
					 * Toast.makeText(getApplicationContext(),
					 * "itemTransType :"+itemTransType, 1).show();
					 */
					double itemPricelogedUnit = Double
							.parseDouble(itemPriceloged);
					double itemCaseQtyVal = Double.parseDouble(itemCaseQty);
					double PricePerItemVal = itemPricelogedUnit
							/ itemCaseQtyVal;
					String PrintPricePerItem = Double.toString(PricePerItemVal);

					String itemSummeryRawIdStr = String
							.valueOf(itemSummeryRawId);

					if (itemRefNo.equals(itemSummeryRawIdStr)) {
						etdminvditem.setText(itemDescription);
						etdminvdunitval.setText(itemCaseQty);
						etdminvdpriceval.setText(PrintPricePerItem);
						etdminvdpricevalunit.setText(itemPriceloged);
						etdminvdcasesval.setText(itemCasesloged);
						etdminvdpiecesval.setText(itemPiecesloged);
						etdminvddiscountval.setText(itemDiscount);
						etdminvdtotitemsval.setText(itemTotInvAmount);
						TextTransType.setText(itemTransType);
						if (itemTransType.equals("22")) {
							strTypePrint = "SA -Sales";
							etdminvdcasesval.setEnabled(true);
							etdminvdpiecesval.setEnabled(true);
							// resetSpinner();
						} else if (itemTransType.equals("25")) {
							strTypePrint = "UR -Re Usable Return";
							etdminvdcasesval.setEnabled(true);
							etdminvdpiecesval.setEnabled(true);
							etdminvddiscountval.setEnabled(true);
						} else if (itemTransType.equals("31")) {
							strTypePrint = "MR -Market Return";
							etdminvdcasesval.setEnabled(true);
							etdminvdpiecesval.setEnabled(true);
						} else if (itemTransType.equals("27")) {
							strTypePrint = "FI -Free Issues";
							etdminvdcasesval.setEnabled(true);
							etdminvdpiecesval.setEnabled(true);
						}
						spinnerdmtranstypeButton.setText(strTypePrint);
						spinnerdmtranstypeButton.setVisibility(0);
					}

				}
			}
			chkItemListRaw.close();
		} else {
			Toast.makeText(getApplicationContext(), "ItemNot Found", 1).show();
		}
		mydb.close();
	}

	// Future use only***To set spinner it self if having any updating selection
	private void resetSpinner() {
		// TODO Auto-generated method stub
		ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
				this, R.array.TransactionTypes,
				android.R.layout.simple_spinner_item);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		SpTransType.setAdapter(adapter);
		SpTransType.setOnItemSelectedListener(new OnItemSelectedListener() {

			public void onItemSelected(AdapterView<?> parent, View view,
					int pos, long id) {
				// TODO Auto-generated method stub
				switch (pos) {
				case 0:
					/*
					 * Toast.makeText(parent.getContext(),
					 * "Please Select Your Choice", Toast.LENGTH_LONG) .show();
					 */
					TextTransType.setText("");
					break;

				case 1:
					/*
					 * Toast.makeText(parent.getContext(), "SA -Sales",
					 * Toast.LENGTH_LONG).show();
					 */
					if (etdminvditem.length() != 0) {
						etdminvddiscountval.setEnabled(true);
					} else {
						etdminvddiscountval.setEnabled(false);
					}

					TextTransType.setText("22");
					break;

				case 2:
					/*
					 * Toast.makeText(parent.getContext(),
					 * "UR -Re Usable Return", Toast.LENGTH_LONG) .show();
					 */
					etdminvddiscountval.setEnabled(false);
					TextTransType.setText("25");
					break;
				case 3:
					/*
					 * Toast.makeText(parent.getContext(), "MR -Market Return",
					 * Toast.LENGTH_LONG).show();
					 */
					etdminvddiscountval.setEnabled(false);
					TextTransType.setText("31");
					break;
				case 4:
					/*
					 * Toast.makeText(parent.getContext(), "FI -Free Issues",
					 * Toast.LENGTH_LONG).show();
					 */
					etdminvddiscountval.setEnabled(false);
					TextTransType.setText("27");
					break;
				}
			}

			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub

			}

		});
	}

	private void setItemsPrice() {
		// TODO Auto-generated method stub
		invitemcode.trim();
		SQLiteDatabase mydb = openOrCreateDatabase(DBNAME,
				Context.MODE_PRIVATE, null);
		String[] cols = { "ItemCode" };
		Cursor chkItemPrice = null;

		try {
			chkItemPrice = mydb.query(ITEM_PRICE, null, null, null, null, null,
					null);
		} catch (Exception e1) {
		}
		if (chkItemPrice != null) {
			if (chkItemPrice.getCount() > 0) {

				while (chkItemPrice.moveToNext()) {
					String itemsUnitsPerCase = etdminvdunitval.getText()
							.toString();
					double currentUnitQty = Double
							.parseDouble(itemsUnitsPerCase);
					String itemcodep = chkItemPrice.getString(2);
					String itempricatcode = chkItemPrice.getString(3);
					String pricecat = itempricatcode.substring(0, 1);
					String itemprice = chkItemPrice.getString(5);
					double currentUnitPrice = Double.parseDouble(itemprice);
					String PrintcurrentUnitPrice = Double
							.toString(currentUnitPrice);
					double currentItemsPrice = currentUnitPrice
							/ currentUnitQty;
					currentItemsPrice = Math.round(currentItemsPrice * 100) / 100.0d;
					String PrintcurrentItemsPrice = Double
							.toString(currentItemsPrice);
					itemcodep.trim();

					if (itemcodep.equals(invitemcode)) {

						if (itempricatcode.equals("WSP001")) {

							etdminvdpriceval.setText(PrintcurrentItemsPrice);
							etdminvdpricevalunit.setText(PrintcurrentUnitPrice);
						} else {

						}
						etdminvdpriceval.setText(PrintcurrentItemsPrice);
						etdminvdpricevalunit.setText(PrintcurrentUnitPrice);
					} else {

					}
				}
			}

		} else {
			Toast.makeText(getApplicationContext(), "ItemNot Found", 1).show();
		}
		chkItemPrice.close();
		mydb.close();
	}

	@Override
	@SuppressWarnings("deprecation")
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.dm_invoice_newdetails);
		{
			Bundle bundle = getIntent().getExtras();
			TagId = bundle.getString("TAGID");
			currentuser();

			populateItemsDetailsList();
			TextTransType = (EditText) findViewById(R.id.dminvtranstypevalue);
			InvHeader = (Button) findViewById(R.id.btninvheader);

			InvSelectNewItem = (Button) findViewById(R.id.btninvdselectitems);
			InvAddNewItem = (Button) findViewById(R.id.btninvaddnewitem);
			InvDeleteItem = (Button) findViewById(R.id.btninvdeleteitem);
			InvUpdateItem = (Button) findViewById(R.id.btninvupdateitem);
			spinnerdmtranstypeButton = (Button) findViewById(R.id.spinnerdmtranstypeButton);
			etdminvditem = (EditText) findViewById(R.id.etdminvditem);

			etdminvdunitval = (EditText) findViewById(R.id.etdminvdunitval); // No
																				// of
																				// items
																				// within
																				// a
																				// case
			etdminvdpriceval = (EditText) findViewById(R.id.etdminvdpriceval); // Price
																				// per
																				// item
			etdminvdpricevalunit = (EditText) findViewById(R.id.etdminvdpricevalunit);
			etdminvdcasesval = (EditText) findViewById(R.id.etdminvdcasesval); // No
																				// of
																				// cases
			etdminvdcasesval
					.addTextChangedListener(filteretdminvdcasesvalWatcher);
			etdminvdpiecesval = (EditText) findViewById(R.id.etdminvdpiecesval); // No
																					// of
																					// pieces
			etdminvdpiecesval
					.addTextChangedListener(filteretdminvdpiecesvalWatcher);
			etdminvddiscountval = (EditText) findViewById(R.id.etdminvddiscountval); // Discounted
																						// value
			etdminvddiscountval
					.addTextChangedListener(filteretdminvddiscountvalWatcher);// change
																				// event
																				// for
			// changing disconts
			etdminvdtotitemsval = (EditText) findViewById(R.id.etdminvdtotitemsval); // Toal
																						// value
																						// after
																						// Discount

			ListAllItems = (LinearLayout) findViewById(R.id.dminvoiceselectitems);
			ListInvItemDetails = (LinearLayout) findViewById(R.id.dminvoiceitemsdetails);

			SpTransType = (Spinner) findViewById(R.id.spinnerdmtranstype);
			showCurrentInvoiceItemsList();
			InvHeader.setOnClickListener(new View.OnClickListener() {
				public void onClick(View view) {
					Intent myIntent = new Intent(view.getContext(),
							DM_InvoiceNew.class);
					myIntent.putExtra("TAGID", "5");
					myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
							| Intent.FLAG_ACTIVITY_NEW_TASK);
					startActivityForResult(myIntent, 0);
					finish();

				}

			});

			InvSelectNewItem.setOnClickListener(new View.OnClickListener() {

				public void onClick(View view) {
					String NewitemCategory = TextTransType.getText().toString();
					if (TextTransType.length() == 0) {

						final AlertDialog alertDialog = new AlertDialog.Builder(
								DM_InvoiceDetails.this).create();
						// Setting Dialog Title
						alertDialog.setTitle("SELECT");
						// Setting Dialog Message
						alertDialog.setMessage("Select Transaction Type");
						// Setting Icon to Dialog
						alertDialog.setIcon(R.drawable.warning);
						// Setting OK Button
						alertDialog.setButton("OK",
								new DialogInterface.OnClickListener() {
									public void onClick(
											final DialogInterface dialog,
											final int which) {
										alertDialog.dismiss();
									}
								});
						// Showing Alert Message
						alertDialog.show();
						return;
					} else {
						InvAddNewItem.setEnabled(true);
						ItemsPerCase = 0.0;
						ItemsPrice = 0.0;
						ItemsCaseTotValue = 0.0;
						NoOfCasesPerItem = 0.0;
						NoOfPiecesPerItem = 0.0;
						ItemsDiscountValue = 0.0;
						TotValForCases = 0.0;
						TotValForPieces = 0.0;
						FinalTotValPerItem = 0.0;
						ListAllItems.setVisibility(view.VISIBLE);
						ListInvItemDetails.setVisibility(view.GONE);
						if (NewitemCategory.equals("22")) {
							etdminvddiscountval.setEnabled(true);
						} else {
							etdminvddiscountval.setEnabled(false);
						}
						etdminvdcasesval.setEnabled(true);
						etdminvdpiecesval.setEnabled(true);
					}
					// ListInvItemDetailsSummery.setVisibility(view.GONE);

				}

			});

			// Select No Of Cases
			etdminvdcasesval.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					currentOption = 99;
					etdminvdpiecesval.setText("");
				}
			});
			// Select No Of Pieces
			etdminvdpiecesval.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					currentOption = 999;
				}
			});
			InvAddNewItem.setOnClickListener(new View.OnClickListener() {
				public void onClick(View view) {
					DELTAG = 77;
					if (etdminvditem.length() == 0) {
						/*
						 * Toast.makeText(getApplicationContext(),
						 * "Select Item..", 1).show();
						 */
						final AlertDialog alertDialog = new AlertDialog.Builder(
								DM_InvoiceDetails.this).create();
						// Setting Dialog Title
						alertDialog.setTitle("SELECT ITEM");
						// Setting Dialog Message
						alertDialog.setMessage("Select Item From List");
						// Setting Icon to Dialog
						alertDialog.setIcon(R.drawable.warning);
						// Setting OK Button
						alertDialog.setButton("OK",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int which) {
										alertDialog.dismiss();
									}
								});
						// Showing Alert Message
						alertDialog.show();
						return;
					} else if (etdminvdtotitemsval.length() == 0) {

						final AlertDialog alertDialog = new AlertDialog.Builder(
								DM_InvoiceDetails.this).create();
						// Setting Dialog Title
						alertDialog.setTitle("ADD QTY");
						// Setting Dialog Message
						alertDialog.setMessage("Enter Item Quantity");
						// Setting Icon to Dialog
						alertDialog.setIcon(R.drawable.warning);
						// Setting OK Button
						alertDialog.setButton("OK",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int which) {
										alertDialog.dismiss();
									}
								});
						// Showing Alert Message
						alertDialog.show();
						return;
					} else if (TextTransType.length() == 0) {

						final AlertDialog alertDialog = new AlertDialog.Builder(
								DM_InvoiceDetails.this).create();
						// Setting Dialog Title
						alertDialog.setTitle("SELECT TYPE");
						// Setting Dialog Message
						alertDialog.setMessage("Select Transaction Type");
						// Setting Icon to Dialog
						alertDialog.setIcon(R.drawable.warning);
						// Setting OK Button
						alertDialog.setButton("OK",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int which) {
										alertDialog.dismiss();
									}
								});
						// Showing Alert Message
						alertDialog.show();
						return;
					} else {
						double calCaseQTY = (ItemsPerCase * NoOfCasesPerItem);
						InvTotItemQTY = NoOfPiecesPerItem + calCaseQTY;
						SelectSequence();
						AddNewInvoiceItem();
					}

				}

			});

			// Update Excisting invoice details raw
			InvUpdateItem.setOnClickListener(new View.OnClickListener() {
				public void onClick(View view) {
					if (etdminvditem.length() == 0) {
						final AlertDialog alertDialog = new AlertDialog.Builder(
								DM_InvoiceDetails.this).create();
						// Setting Dialog Title
						alertDialog.setTitle("SELECT ITEM");
						// Setting Dialog Message
						alertDialog.setMessage("Select Item From List");
						// Setting Icon to Dialog
						alertDialog.setIcon(R.drawable.warning);
						// Setting OK Button
						alertDialog.setButton("OK",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int which) {
										alertDialog.dismiss();
									}
								});
						// Showing Alert Message
						alertDialog.show();

						return;
					} else if (etdminvdtotitemsval.length() == 0) {
						final AlertDialog alertDialog = new AlertDialog.Builder(
								DM_InvoiceDetails.this).create();
						// Setting Dialog Title
						alertDialog.setTitle("ADD QTY");
						// Setting Dialog Message
						alertDialog.setMessage("Enter Item Quantity");
						// Setting Icon to Dialog
						alertDialog.setIcon(R.drawable.warning);
						// Setting OK Button
						alertDialog.setButton("OK",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int which) {
										alertDialog.dismiss();
									}
								});
						// Showing Alert Message
						alertDialog.show();
						return;
					} else if (TextTransType.length() == 0) {
						final AlertDialog alertDialog = new AlertDialog.Builder(
								DM_InvoiceDetails.this).create();
						// Setting Dialog Title
						alertDialog.setTitle("SELECT TYPE");
						// Setting Dialog Message
						alertDialog.setMessage("Select Transaction Type");
						// Setting Icon to Dialog
						alertDialog.setIcon(R.drawable.warning);
						// Setting OK Button
						alertDialog.setButton("OK",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int which) {
										alertDialog.dismiss();
									}
								});
						// Showing Alert Message
						alertDialog.show();
						return;
					} else {
						double calCaseQTY = (ItemsPerCase * NoOfCasesPerItem);
						InvTotItemQTY = NoOfPiecesPerItem + calCaseQTY;
						UpdateInvoiceItem();
					}

				}

			});
			InvDeleteItem.setOnClickListener(new View.OnClickListener() {
				public void onClick(View view) {
					DELTAG = 88;
					if (etdminvditem.length() == 0) {
						final AlertDialog alertDialog = new AlertDialog.Builder(
								DM_InvoiceDetails.this).create();
						// Setting Dialog Title
						alertDialog.setTitle("SELECT ITEM");
						// Setting Dialog Message
						alertDialog.setMessage("Select Item From List");
						// Setting Icon to Dialog
						alertDialog.setIcon(R.drawable.warning);
						// Setting OK Button
						alertDialog.setButton("OK",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int which) {
										alertDialog.dismiss();
									}
								});
						// Showing Alert Message
						alertDialog.show();
						return;
					} else if (etdminvdtotitemsval.length() == 0) {
						final AlertDialog alertDialog = new AlertDialog.Builder(
								DM_InvoiceDetails.this).create();
						// Setting Dialog Title
						alertDialog.setTitle("ADD QTY");
						// Setting Dialog Message
						alertDialog.setMessage("Enter Item Quantity");
						// Setting Icon to Dialog
						alertDialog.setIcon(R.drawable.warning);
						// Setting OK Button
						alertDialog.setButton("OK",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int which) {
										alertDialog.dismiss();
									}
								});
						// Showing Alert Message
						alertDialog.show();
						return;
					} else if (TextTransType.length() == 0) {
						final AlertDialog alertDialog = new AlertDialog.Builder(
								DM_InvoiceDetails.this).create();
						// Setting Dialog Title
						alertDialog.setTitle("SELECT TYPE");
						// Setting Dialog Message
						alertDialog.setMessage("Select Transaction Type");
						// Setting Icon to Dialog
						alertDialog.setIcon(R.drawable.warning);
						// Setting OK Button
						alertDialog.setButton("OK",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int which) {
										alertDialog.dismiss();
									}
								});
						// Showing Alert Message
						alertDialog.show();
						return;
					} else {
						double calCaseQTY = (ItemsPerCase * NoOfCasesPerItem);
						InvTotItemQTY = NoOfPiecesPerItem + calCaseQTY;
						DeleteInvoiceItem();
					}

				}

			});

			ArrayAdapter<CharSequence> adapter = ArrayAdapter
					.createFromResource(this, R.array.TransactionTypes,
							android.R.layout.simple_spinner_item);
			adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
			SpTransType.setAdapter(adapter);
			SpTransType.setOnItemSelectedListener(new OnItemSelectedListener() {

				public void onItemSelected(AdapterView<?> parent, View view,
						int pos, long id) {
					// TODO Auto-generated method stub
					switch (pos) {
					case 0:
						/*
						 * Toast.makeText(parent.getContext(),
						 * "Please Select Your Choice", Toast.LENGTH_LONG)
						 * .show();
						 */
						TextTransType.setText("");
						break;

					case 1:
						/*
						 * Toast.makeText(parent.getContext(), "SA -Sales",
						 * Toast.LENGTH_LONG).show();
						 */
						if (etdminvditem.length() != 0) {
							etdminvddiscountval.setEnabled(true);
						} else {
							etdminvddiscountval.setEnabled(false);
						}
						checkTransTypeDupItem();
						if (CheckAdd == 90) {
							final AlertDialog alertDialog = new AlertDialog.Builder(
									DM_InvoiceDetails.this).create();
							// Setting Dialog Title
							alertDialog.setTitle("ADD NEW ITEM");
							// Setting Dialog Message
							alertDialog.setMessage("Item Already Entered With Same Type");
							// Setting Icon to Dialog
							alertDialog.setIcon(R.drawable.warning);
							// Setting OK Button
							alertDialog.setButton("OK",
									new DialogInterface.OnClickListener() {
										public void onClick(
												DialogInterface dialog,
												int which) {
											CheckAdd =0;
											alertDialog.dismiss();
										}
									});
							// Showing Alert Message
							alertDialog.show();

						} else {
							ChkType = 22;
							checkTransTypeDupItem();
							TextTransType.setText("22");
							strType = "SA";
						}
						break;

					case 2:
						/*
						 * Toast.makeText(parent.getContext(),
						 * "UR -Re Usable Return", Toast.LENGTH_LONG) .show();
						 */
						ChkType = 25;
						checkTransTypeDupItem();
						if (CheckAdd == 90) {
							final AlertDialog alertDialog = new AlertDialog.Builder(
									DM_InvoiceDetails.this).create();
							// Setting Dialog Title
							alertDialog.setTitle("ADD NEW ITEM");
							// Setting Dialog Message
							alertDialog.setMessage("Item Already Entered With Same Type");
							// Setting Icon to Dialog
							alertDialog.setIcon(R.drawable.warning);
							// Setting OK Button
							alertDialog.setButton("OK",
									new DialogInterface.OnClickListener() {
										public void onClick(
												DialogInterface dialog,
												int which) {
											CheckAdd =0;
											alertDialog.dismiss();
										}
									});
							// Showing Alert Message
							alertDialog.show();
						}
							else{
						etdminvddiscountval.setEnabled(false);
						TextTransType.setText("25");
						strType = "UR";
							}
						break;
					case 3:
						/*
						 * Toast.makeText(parent.getContext(),
						 * "MR -Market Return", Toast.LENGTH_LONG).show();
						 */
						ChkType = 31;
						checkTransTypeDupItem();
						if (CheckAdd == 90) {
							final AlertDialog alertDialog = new AlertDialog.Builder(
									DM_InvoiceDetails.this).create();
							// Setting Dialog Title
							alertDialog.setTitle("ADD NEW ITEM");
							// Setting Dialog Message
							alertDialog.setMessage("Item Already Entered With Same Type");
							// Setting Icon to Dialog
							alertDialog.setIcon(R.drawable.warning);
							// Setting OK Button
							alertDialog.setButton("OK",
									new DialogInterface.OnClickListener() {
										public void onClick(
												DialogInterface dialog,
												int which) {
											CheckAdd =0;
											alertDialog.dismiss();
										}
									});
							// Showing Alert Message
							alertDialog.show();
						}else{
						etdminvddiscountval.setEnabled(false);
						TextTransType.setText("31");
						strType = "MR";
						}
						break;
					case 4:
						/*
						 * Toast.makeText(parent.getContext(),
						 * "FI -Free Issues", Toast.LENGTH_LONG).show();
						 */
						ChkType = 27;
						checkTransTypeDupItem();
						if (CheckAdd == 90) {
							final AlertDialog alertDialog = new AlertDialog.Builder(
									DM_InvoiceDetails.this).create();
							// Setting Dialog Title
							alertDialog.setTitle("ADD NEW ITEM");
							// Setting Dialog Message
							alertDialog.setMessage("Item Already Entered");
							// Setting Icon to Dialog
							alertDialog.setIcon(R.drawable.warning);
							// Setting OK Button
							alertDialog.setButton("OK",
									new DialogInterface.OnClickListener() {
										public void onClick(
												DialogInterface dialog,
												int which) {
											alertDialog.dismiss();
										}
									});
							// Showing Alert Message
							alertDialog.show();

						} else {
							etdminvddiscountval.setEnabled(false);
							TextTransType.setText("27");
							strType = "FI";
						}

						break;
					}
				}

				private void checkTransTypeDupItem() {
					// TODO Auto-generated method stub
					SQLiteDatabase mydb = openOrCreateDatabase(DBNAME,
							Context.MODE_PRIVATE, null);
					Cursor chkItemLocatedChkDup = null;
					try {
						chkItemLocatedChkDup = mydb
								.query(INV_DETAILS, null, "Itemcode='"
										+ invitemcode
										+ "' AND refInvoiceDetNo='"
										+ LatestInvNumberStr + "'AND TxnType='"
										+ ChkType + "'", null, null, null, null);
					} catch (Exception e1) {
					}
					if (chkItemLocatedChkDup != null) {
						if (chkItemLocatedChkDup.getCount() > 0) {
							CheckAdd = 90;
						} else {
							CheckAdd = 0;
						}
					}

				}

				public void onNothingSelected(AdapterView<?> arg0) {
					// TODO Auto-generated method stub

				}

			});

		}

	}

	private void currentuser() {
		// TODO Auto-generated method stub
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor selectCurrentuserrec = null;
		try {
			selectCurrentuserrec = mydb.query(TEMP_USER, null, null, null,
					null, null, null);
		} catch (Exception e) {
		}
		if (selectCurrentuserrec != null) {
			if (selectCurrentuserrec.getCount() > 0) {
				while (selectCurrentuserrec.moveToNext()) {
					currentUser = selectCurrentuserrec.getString(1);
					String currentStNoRef = selectCurrentuserrec.getString(4);
					if (currentStNoRef.equals("0")) {
						currentStOrdNo = "0";
					} else {
						currentStOrdNo = currentStNoRef;
					}

				}
			}
		}
		currentInvoiceNo();// Get current invoice temp
		selectCurrentuserrec.close();
		mydb.close();
	}

	private void currentInvoiceNo() {
		// TODO Auto-generated method stub
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor selectLastinvrec = null;
		String columsup[] = { "tempRepInvSerial" };
		try {
			selectLastinvrec = mydb.query(TEMP_REP_INVOICESUMERY, null,
					"repusername='" + currentUser + "' AND invlateststate='9'",
					null, null, null, null);
		} catch (Exception e) {
		}
		if (selectLastinvrec != null) {
			if (selectLastinvrec.getCount() > 0) {
				while (selectLastinvrec.moveToNext()) {
					String LatestInvCodeStr = selectLastinvrec.getString(3);
					LatestInvNumberStr = selectLastinvrec.getString(4);
					String LatestInvValueStr = selectLastinvrec.getString(7);
					double LatestInvValue = Double
							.parseDouble(LatestInvValueStr);
					TotInvoiceAmount = LatestInvValue;
					// Formating invoice number
					String LatestInvDisValueStr = selectLastinvrec.getString(8);
					double LatestInvDisValue = Double
							.parseDouble(LatestInvDisValueStr);
					TotInvoiceDiscountAmount = LatestInvDisValue;
					if (LatestInvNumberStr.length() == 1) {
						String newInvNumberStr = "00000" + LatestInvNumberStr;
						currentInvoiceTempRefCode = LatestInvCodeStr + "/"
								+ newInvNumberStr;
					} else if (LatestInvNumberStr.length() == 2) {
						String newInvNumberStr = "0000" + LatestInvNumberStr;
						currentInvoiceTempRefCode = LatestInvCodeStr + "/"
								+ newInvNumberStr;
					} else if (LatestInvNumberStr.length() == 3) {
						String newInvNumberStr = "000" + LatestInvNumberStr;
						currentInvoiceTempRefCode = LatestInvCodeStr + "/"
								+ newInvNumberStr;
					} else if (LatestInvNumberStr.length() == 4) {
						String newInvNumberStr = "00" + LatestInvNumberStr;
						currentInvoiceTempRefCode = LatestInvCodeStr + "/"
								+ newInvNumberStr;
					} else if (LatestInvNumberStr.length() == 5) {
						String newInvNumberStr = "0" + LatestInvNumberStr;
						currentInvoiceTempRefCode = LatestInvCodeStr + "/"
								+ newInvNumberStr;
					} else {
						currentInvoiceTempRefCode = LatestInvCodeStr + "/"
								+ LatestInvNumberStr;
					}
					currentInvoiceTempNo = LatestInvNumberStr;
					String LatestNoofItemsStr = selectLastinvrec.getString(19);
					double LatestNoofItemsValue = Double
							.parseDouble(LatestNoofItemsStr);
					NoOfItemsPerInvoice = LatestNoofItemsValue;
				}
			} else {
				Toast.makeText(getApplicationContext(), "First Invoice 1****",
						Toast.LENGTH_SHORT).show();
			}
		} else {

			Toast.makeText(getApplicationContext(), "First Invoice 1****",
					Toast.LENGTH_SHORT).show();
		}
		selectLastinvrec.close();
		mydb.close();
	}

	// Get latest sequence number
	protected void SelectSequence() {

		// Check Previously item Enter or Not
		SQLiteDatabase mydb = openOrCreateDatabase(DBNAME,
				Context.MODE_PRIVATE, null);
		Cursor chkItemSequence = null;

		String query = "SELECT invdet_id from FinvDet order by invdet_id DESC limit 1";
		Cursor c = mydb.rawQuery(query, null);
		if (c != null && c.moveToLast()) {
			lastId = c.getLong(0);
			strlastId = Long.toString(lastId);
		}

		try {
			chkItemSequence = mydb.query(INV_DETAILS, null, "invdet_id='"
					+ strlastId + "'", null, null, null, null);
		} catch (Exception e1) {
		}

		try {
			if (chkItemSequence != null) {
				if (chkItemSequence.getCount() > 0) {
					while (chkItemSequence.moveToNext()) {
						String rawid = chkItemSequence.getString(0);
						invDetLastRefNo = chkItemSequence.getString(28);
						String strinvDetLastSequence = chkItemSequence
								.getString(4);
						invDetLastSequence = Integer
								.parseInt(strinvDetLastSequence);
						if (invDetLastRefNo.equals(currentInvoiceTempNo)) {
							invDetLastSequence = invDetLastSequence + 1;
						} else {
							invDetLastSequence = 1;
						}
					}
				} else {
					invDetLastSequence = 1;
				}
			} else {
				invDetLastSequence = 1;
			}

		} catch (Exception e1) {
			Toast.makeText(getApplicationContext(), "Error Select Sequence..",
					Toast.LENGTH_SHORT).show();
		}
		chkItemSequence.close();
		mydb.close();

	}

	// Save invoice item details in to DQLite DB
	protected void AddNewInvoiceItem() {
		// TODO Auto-generated meAddNewInvoiceItemthod stub
		etdminvdcasesval.setEnabled(false);
		etdminvdpiecesval.setEnabled(false);
		String CurrentType = TextTransType.getText().toString();

		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		try {
			ContentValues newitemdetailrecord = new ContentValues();
			newitemdetailrecord.put("RefNo", currentInvoiceTempRefCode);
			newitemdetailrecord.put("TxnDate", getCurrentTimeString()
					.toString());
			newitemdetailrecord.put("TxnType", TextTransType.getText()
					.toString());
			newitemdetailrecord.put("SeqNo", invDetLastSequence);
			newitemdetailrecord.put("Itemcode", invitemcode);
			newitemdetailrecord.put("Txnseqno", invDetLastSequence);
			newitemdetailrecord.put("SellPrice", etdminvdpricevalunit.getText()
					.toString());
			newitemdetailrecord.put("BSellPrice", etdminvdpricevalunit
					.getText().toString());
			newitemdetailrecord.put("TSellPrice", etdminvdpricevalunit
					.getText().toString());
			newitemdetailrecord.put("BTSellPrice", etdminvdpricevalunit
					.getText().toString());
			newitemdetailrecord.put("CostPrice", etdminvdpricevalunit.getText()
					.toString());
			if (etdminvdcasesval.length() != 0) {
				newitemdetailrecord.put("CaseQty", etdminvdcasesval.getText()
						.toString());
			} else {
				newitemdetailrecord.put("CaseQty", "0");
			}
			newitemdetailrecord.put("Type", strType);
			if (etdminvdpiecesval.length() != 0) {
				newitemdetailrecord.put("PiceQty", etdminvdpiecesval.getText()
						.toString());
			} else {
				newitemdetailrecord.put("PiceQty", "0");
			}
			newitemdetailrecord.put("Qty", InvTotItemQTY);
			newitemdetailrecord.put("BalQty", InvTotItemQTY);
			newitemdetailrecord.put("DisPer", "0.00");

			if (etdminvddiscountval.length() != 0) {
				newitemdetailrecord.put("DisAmt", etdminvddiscountval.getText()
						.toString());
			} else {
				newitemdetailrecord.put("DisAmt", "0.00");
			}
			if (etdminvddiscountval.length() != 0) {
				newitemdetailrecord.put("BDisAmt", etdminvddiscountval
						.getText().toString());
			} else {
				newitemdetailrecord.put("BDisAmt", "0.00");
			}

			if (etdminvddiscountval.length() != 0) {
				String currentDiscountTot = etdminvddiscountval.getText()
						.toString();
				double valueDiscountItems = Double
						.parseDouble(currentDiscountTot);
				double valueTotDisItems = TotInvoiceDiscountAmount;
				TotInvoiceDiscountAmount = valueDiscountItems
						+ valueTotDisItems;
			}

			String TotoalItemDisInvoice = Double
					.toString(TotInvoiceDiscountAmount);

			newitemdetailrecord.put("TaxAmt", "0");
			newitemdetailrecord.put("BTaxAmt", "0");
			newitemdetailrecord.put("Amt", etdminvdtotitemsval.getText()
					.toString());
			String currentTot = etdminvdtotitemsval.getText().toString();
			double valueItems = Double.parseDouble(currentTot);
			double valueTotItems = TotInvoiceAmount;
			double valueTotReturnItems = TotInvoiceReturnAmount;
			if (CurrentType.equals("22")) {
				TotInvoiceAmount = valueItems + valueTotItems;
			} else if (CurrentType.equals("27")) {
				TotInvoiceAmount = valueTotItems;
			} else {
				TotInvoiceReturnAmount = valueTotReturnItems + valueItems;
				TotInvoiceAmount = valueTotItems - valueItems;
			}

			String TotoalInvoice = Double.toString(TotInvoiceAmount);

			newitemdetailrecord.put("BAmt", etdminvdtotitemsval.getText()
					.toString());

			newitemdetailrecord.put("ReaCode", "0");
			newitemdetailrecord.put("Linkrec", "0");
			newitemdetailrecord.put("RecordId", "0");
			newitemdetailrecord.put("itemDescription", etdminvditem.getText()
					.toString());
			newitemdetailrecord.put("refInvoiceDetNo", currentInvoiceTempNo);
			newitemdetailrecord.put("refInvoiceDetCode",
					currentInvoiceTempRefCode);
			newitemdetailrecord.put("refInvitemCaseQty", etdminvdunitval
					.getText().toString());
			newitemdetailrecord.put("refInvStockOrderNo", currentStOrdNo);

			mydb.insert(INV_DETAILS, null, newitemdetailrecord);
			// updateItemLocationQty();
			updateInvoiceValue();

		} catch (Exception e) {
			Toast.makeText(getApplicationContext(), "Error Occured..",
					Toast.LENGTH_SHORT).show();
		}
		// clearFields();
		mydb.close();

	}

	private void updateItemLocationQty() {
		// TODO Auto-generated method stub

	}

	// Update current invoice item details in to DQLite DB
	protected void UpdateInvoiceItem() {
		// TODO Auto-generated method stub
		etdminvdcasesval.setEnabled(false);
		etdminvdpiecesval.setEnabled(false);
		String CurrentType = TextTransType.getText().toString();

		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		try {
			ContentValues newitemdetailrecord = new ContentValues();
			newitemdetailrecord.put("RefNo", currentInvoiceTempRefCode);
			newitemdetailrecord.put("TxnDate", getCurrentTimeString()
					.toString());
			newitemdetailrecord.put("TxnType", TextTransType.getText()
					.toString());
			newitemdetailrecord.put("SeqNo", invDetLastSequence);
			newitemdetailrecord.put("Itemcode", invitemcode);
			newitemdetailrecord.put("Txnseqno", invDetLastSequence);
			newitemdetailrecord.put("SellPrice", etdminvdpricevalunit.getText()
					.toString());
			newitemdetailrecord.put("BSellPrice", etdminvdpricevalunit
					.getText().toString());
			newitemdetailrecord.put("TSellPrice", etdminvdpricevalunit
					.getText().toString());
			newitemdetailrecord.put("BTSellPrice", etdminvdpricevalunit
					.getText().toString());
			newitemdetailrecord.put("CostPrice", etdminvdpricevalunit.getText()
					.toString());
			if (etdminvdcasesval.length() != 0) {
				newitemdetailrecord.put("CaseQty", etdminvdcasesval.getText()
						.toString());
			} else {
				newitemdetailrecord.put("CaseQty", "0");
			}
			newitemdetailrecord.put("Type", strType);
			if (etdminvdpiecesval.length() != 0) {
				newitemdetailrecord.put("PiceQty", etdminvdpiecesval.getText()
						.toString());
			} else {
				newitemdetailrecord.put("PiceQty", "0");
			}
			newitemdetailrecord.put("Qty", InvTotItemQTY);
			newitemdetailrecord.put("BalQty", InvTotItemQTY);
			newitemdetailrecord.put("DisPer", "0.00");
			if (etdminvddiscountval.length() != 0) {
				newitemdetailrecord.put("DisAmt", etdminvddiscountval.getText()
						.toString());
			} else {
				newitemdetailrecord.put("DisAmt", "0.00");
			}
			if (etdminvddiscountval.length() != 0) {
				newitemdetailrecord.put("BDisAmt", etdminvddiscountval
						.getText().toString());
			} else {
				newitemdetailrecord.put("BDisAmt", "0.00");
			}
			if (etdminvddiscountval.length() != 0) {
				String currentDiscountTot = etdminvddiscountval.getText()
						.toString();
				double valueDiscountItems = Double
						.parseDouble(currentDiscountTot);
				double valueTotDisItems = TotInvoiceDiscountAmount;
				TotInvoiceDiscountAmount = valueDiscountItems
						+ valueTotDisItems;
			}

			String TotoalItemDisInvoice = Double
					.toString(TotInvoiceDiscountAmount);

			newitemdetailrecord.put("TaxAmt", "0");
			newitemdetailrecord.put("BTaxAmt", "0");
			newitemdetailrecord.put("Amt", etdminvdtotitemsval.getText()
					.toString());
			String currentTot = etdminvdtotitemsval.getText().toString();
			double valueItems = Double.parseDouble(currentTot);
			double valueTotItems = TotInvoiceAmount;
			double valueTotReturnItems = TotInvoiceReturnAmount;
			if (CurrentType.equals("22")) {
				TotInvoiceAmount = valueItems + valueTotItems;
			} else if (CurrentType.equals("27")) {
				TotInvoiceAmount = valueTotItems;
			} else {
				TotInvoiceReturnAmount = valueTotReturnItems + valueItems;
				TotInvoiceAmount = valueTotItems - valueItems;
			}

			String TotoalInvoice = Double.toString(TotInvoiceAmount);

			newitemdetailrecord.put("BAmt", etdminvdtotitemsval.getText()
					.toString());

			newitemdetailrecord.put("ReaCode", "0");
			newitemdetailrecord.put("Linkrec", "0");
			newitemdetailrecord.put("RecordId", "0");
			newitemdetailrecord.put("itemDescription", etdminvditem.getText()
					.toString());
			newitemdetailrecord.put("refInvoiceDetNo", currentInvoiceTempNo);
			newitemdetailrecord.put("refInvoiceDetCode",
					currentInvoiceTempRefCode);
			newitemdetailrecord.put("refInvitemCaseQty", etdminvdunitval
					.getText().toString());

			mydb.update(INV_DETAILS, newitemdetailrecord, "invdet_id ='"
					+ itemSummeryRawId + "'", null);

			final AlertDialog alertDialog = new AlertDialog.Builder(
					DM_InvoiceDetails.this).create();
			// Setting Dialog Title
			alertDialog.setTitle("UPDATE");
			// Setting Dialog Message
			alertDialog.setMessage("Record Updated Successfully");
			// Setting Icon to Dialog
			alertDialog.setIcon(R.drawable.warning);
			// Setting OK Button
			alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					alertDialog.dismiss();
				}
			});
			// Showing Alert Message
			alertDialog.show();
			updateInvoiceValue();

		} catch (Exception e) {
			Toast.makeText(getApplicationContext(), "Error Occured..",
					Toast.LENGTH_SHORT).show();
		}
		// clearFields();
		mydb.close();
	}

	// Delete current records from the grid
	protected void DeleteInvoiceItem() {

		// TODO Auto-generated method stub
		etdminvdcasesval.setEnabled(false);
		etdminvdpiecesval.setEnabled(false);
		String CurrentType = TextTransType.getText().toString();

		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		try {
			mydb.delete(INV_DETAILS, "invdet_id ='" + itemSummeryRawId + "'",
					null);

			final AlertDialog alertDialog = new AlertDialog.Builder(
					DM_InvoiceDetails.this).create();
			// Setting Dialog Title
			alertDialog.setTitle("DELETE");
			// Setting Dialog Message
			alertDialog.setMessage("Record Deleted Successfully");
			// Setting Icon to Dialog
			alertDialog.setIcon(R.drawable.warning);
			// Setting OK Button
			alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					alertDialog.dismiss();

				}
			});
			// Showing Alert Message
			// alertDialog.show();
			showCurrentInvoiceItemsList();
			updateInvoiceValue();

		} catch (Exception e) {
			Toast.makeText(getApplicationContext(), "Error Occured..",
					Toast.LENGTH_SHORT).show();
		}

		mydb.close();
	}

	// *****Updating Total invoice value in to invoice summery table once add
	// new item
	private void updateInvoiceValue() {
		// TODO Auto-generated method stub
		NoOfItemsPerInvoice = NoOfItemsPerInvoice + 1;
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor selectLastinvrecup = null;
		String columsup[] = { "tempRepInvSerial" };

		try {
			selectLastinvrecup = mydb.query(TEMP_REP_INVOICESUMERY, null,
					"repusername='" + currentUser + "' AND tempRepInvSerial='"
							+ LatestInvNumberStr + "'", null, null, null, null);
		} catch (Exception e) {
		}
		try {
			if (selectLastinvrecup != null) {
				if (selectLastinvrecup.getCount() > 0) {
					while (selectLastinvrecup.moveToNext()) {
						ContentValues valueupdate = new ContentValues();
						String LatestInvNumberStr = selectLastinvrecup
								.getString(0);
						valueupdate.put("activeInvoiceValue", TotInvoiceAmount);
						valueupdate.put("activeInvoiceReturnValue",
								TotInvoiceReturnAmount);
						valueupdate.put("activeInvItemDiscount",
								TotInvoiceDiscountAmount);
						valueupdate.put("invoiceComplete", "1");// Invoice in
																// Active mode
																// Complete
						valueupdate
								.put("invoiceNoOfItems", NoOfItemsPerInvoice);// Invoice
																				// in
						// Active mode
						// Complete
						mydb.update(TEMP_REP_INVOICESUMERY, valueupdate,
								"remprepinv_id ='" + LatestInvNumberStr + "'",
								null);

					}
				} else {

					/*
					 * Toast.makeText(getApplicationContext(),
					 * "Error in update", Toast.LENGTH_SHORT).show();
					 */
				}
				selectLastinvrecup.close();
			}

			else {
				/*
				 * Toast.makeText(getApplicationContext(), "Error in update",
				 * Toast.LENGTH_SHORT).show();
				 */
			}
		} catch (Exception e) {
		}
		clearFields();
		selectLastinvrecup.close();
		mydb.close();
	}

	private void showCurrentInvoiceItemsList() {
		// TODO Auto-generated method stub
		ListView lvtypedes = (ListView) findViewById(R.id.dminvoiceitemsdetlist);
		// create the grid item mapping
		String[] fromtrdes = new String[] { "coldes_1", "coldes_2", "coldes_3",
				"coldes_4" };
		int[] totrdes = new int[] { R.id.itemrawdetails, R.id.itemcases,
				R.id.itempieces, R.id.btnitemrawdetails };
		// prepare the list of all records
		List<HashMap<String, String>> fillMapstrdes = new ArrayList<HashMap<String, String>>();

		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor allrowitemsdes = null;
		String columsup[] = { "refInvoiceDetCode" };

		try {
			allrowitemsdes = mydb.query(INV_DETAILS, null, "refInvoiceDetNo='"
					+ LatestInvNumberStr + "'", null, null, null, null);
		} catch (Exception e) {
		}
		if (allrowitemsdes != null) {
			if (allrowitemsdes.getCount() > 0) {
				while (allrowitemsdes.moveToNext()) {
					// ItemCode = 5 /cases 12 /pieces 14
					String rawItemRef = allrowitemsdes.getString(0);
					String rawItemCode = allrowitemsdes.getString(5);
					String rawItemCases = allrowitemsdes.getString(12);
					String rawItemPieces = allrowitemsdes.getString(14);
					String rawItemDescription = allrowitemsdes.getString(27);

					String rawitemsdet = rawItemRef + "/" + rawItemCode + "/"
							+ rawItemCases + "/" + rawItemPieces + "/"
							+ rawItemDescription;

					HashMap<String, String> maptrdes = new HashMap<String, String>();
					maptrdes.put("coldes_1", rawItemDescription);
					maptrdes.put("coldes_2", rawItemCases);
					maptrdes.put("coldes_3", rawItemPieces);
					maptrdes.put("coldes_4", rawitemsdet);
					fillMapstrdes.add(maptrdes);
				}
				// fill in the grid_item layout
				SimpleAdapter adaptertrdes = new SimpleAdapter(this,
						fillMapstrdes, R.layout.dm_invoice_item_list_raw,
						fromtrdes, totrdes);
				int rawcount = allrowitemsdes.getCount();
				String strI = Integer.toString(rawcount);
				lvtypedes.setAdapter(adaptertrdes);

			}
			int recRemCount = allrowitemsdes.getCount();
			if (recRemCount == 0 && DELTAG == 88) {
				Intent myIntent = new Intent(this, DM_InvoiceDetails.class);
				myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
						| Intent.FLAG_ACTIVITY_NEW_TASK);
				myIntent.putExtra("TAGID", "3");
				startActivityForResult(myIntent, 0);
				DELTAG = 77;
			}
		}
		// lvtypedes.invalidateViews();
		allrowitemsdes.close();
		mydb.close();
	}

	private void showCurrentInvoiceItemsLoading() {
		// TODO Auto-generated method stub
		ListView lvtypedes = (ListView) findViewById(R.id.dminvoiceitemsdetlist);
		// create the grid item mapping
		String[] fromtrdes = new String[] { "coldes_1", "coldes_2", "coldes_3",
				"coldes_4" };
		int[] totrdes = new int[] { R.id.itemrawdetails, R.id.itemcases,
				R.id.itempieces, R.id.btnitemrawdetails };
		// prepare the list of all records
		List<HashMap<String, String>> fillMapstrdes = new ArrayList<HashMap<String, String>>();

		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor allrowitemsdes = null;
		String columsup[] = { "refInvoiceDetCode" };

		try {
			allrowitemsdes = mydb.query(INV_DETAILS, columsup,
					"refInvoiceDetCode='" + currentInvoiceTempRefCode + "'",
					null, null, null, null);
		} catch (Exception e) {
		}
		if (allrowitemsdes != null) {
			if (allrowitemsdes.getCount() > 0) {
				while (allrowitemsdes.moveToNext()) {
					// ItemCode = 5 /cases 12 /pieces 14
					String rawItemRef = allrowitemsdes.getString(0);
					String rawItemCode = allrowitemsdes.getString(5);
					String rawItemCases = allrowitemsdes.getString(12);
					String rawItemPieces = allrowitemsdes.getString(14);
					String rawItemDescription = allrowitemsdes.getString(27);

					String rawitemsdet = rawItemRef + "/" + rawItemCode + "/"
							+ rawItemCases + "/" + rawItemPieces + "/"
							+ rawItemDescription;

					HashMap<String, String> maptrdes = new HashMap<String, String>();
					maptrdes.put("coldes_1", rawItemDescription);
					maptrdes.put("coldes_2", rawItemCases);
					maptrdes.put("coldes_3", rawItemPieces);
					maptrdes.put("coldes_4", rawitemsdet);
					fillMapstrdes.add(maptrdes);

				}
				// fill in the grid_item layout
				SimpleAdapter adaptertrdes = new SimpleAdapter(this,
						fillMapstrdes, R.layout.dm_invoice_item_list_raw,
						fromtrdes, totrdes);
				lvtypedes.setAdapter(adaptertrdes);
			}
		}
		allrowitemsdes.close();
		mydb.close();
	}

	private void clearFields() {
		// TODO Auto-generated method stub

		etdminvditem.setText("");
		etdminvdunitval.setText("");
		etdminvdpriceval.setText("");
		etdminvdpricevalunit.setText("");
		etdminvdcasesval.setText("");
		etdminvdpiecesval.setText("");
		etdminvddiscountval.setText("");
		etdminvdtotitemsval.setText("");
		// TextTransType.setText("");

		showCurrentInvoiceItemsList();
	}

	private void populateItemsDetailsList() {
		// TODO Auto-generated method stub
		ListView lvtypedes = (ListView) findViewById(R.id.listviewItemsDetails);
		// create the grid item mapping
		String[] fromtrdes = new String[] { "coldes_1", "coldes_2" };
		int[] totrdes = new int[] { R.id.invoiceitemsdet, R.id.invitemsname };
		// prepare the list of all records
		List<HashMap<String, String>> fillMapstrdes = new ArrayList<HashMap<String, String>>();

		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor curPopItemsListDet = null;
		try {
			curPopItemsListDet = mydb.query(ITEMS, null, null, null, null,
					null, null);
		} catch (Exception e) {
		}
		if (curPopItemsListDet != null) {
			if (curPopItemsListDet.getCount() > 0) {
				while (curPopItemsListDet.moveToNext()) {
					String itemskucode = curPopItemsListDet.getString(1);
					String itemcode = curPopItemsListDet.getString(2);
					String itemname = curPopItemsListDet.getString(4);
					String itemsincase = curPopItemsListDet.getString(28);

					String rawitemsdet = itemskucode + "/" + itemcode + "/"
							+ itemname + "/" + itemsincase;
					HashMap<String, String> maptrdes = new HashMap<String, String>();
					maptrdes.put("coldes_1", rawitemsdet);
					maptrdes.put("coldes_2", itemname);
					fillMapstrdes.add(maptrdes);

				}
				// fill in the grid_item layout
				SimpleAdapter adaptertrdes = new SimpleAdapter(this,
						fillMapstrdes, R.layout.dm_cusitems_list_raw,
						fromtrdes, totrdes);
				lvtypedes.setAdapter(adaptertrdes);
			}
		}
		curPopItemsListDet.close();
		mydb.close();
	}

	@Override
	public void onBackPressed() {
		// Do Here what ever you want do on back press;
	}

	private String getCurrentTimeString() {
		Calendar c = Calendar.getInstance();
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String formattedDate = df.format(c.getTime());
		return formattedDate;
	}

	// ****************Text Change Events
	// Handling********************************

	// ***********************************************************************************
	private TextWatcher filteretdminvdcasesvalWatcher = new TextWatcher() {

		public void afterTextChanged(Editable s) {
			if (etdminvdcasesval.length() != 0) {
				String Item_PerCase = etdminvdunitval.getText().toString();
				ItemsPerCase = Double.parseDouble(Item_PerCase);
				String Item_Price = etdminvdpriceval.getText().toString();
				ItemsPrice = Double.parseDouble(Item_Price);
				String Item_PriceUnits = etdminvdpricevalunit.getText()
						.toString();
				ItemsCaseTotValue = Double.parseDouble(Item_PriceUnits);
				String Item_Cases = etdminvdcasesval.getText().toString();
				NoOfCasesPerItem = Double.parseDouble(Item_Cases);

				// ItemsCaseTotValue = (ItemsPerCase * ItemsPrice);

				if (etdminvddiscountval.length() != 0) {
					String Item_Discounting = etdminvddiscountval.getText()
							.toString();
					ItemsDiscountValue = Double.parseDouble(Item_Discounting);
				} else {
					ItemsDiscountValue = 0.0;
				}
				if (etdminvdpiecesval.length() != 0) {
					String Item_Pieces = etdminvdpiecesval.getText().toString();
					NoOfPiecesPerItem = Double.parseDouble(Item_Pieces);

					TotValForCases = (ItemsCaseTotValue * NoOfCasesPerItem);
					TotValForPieces = (NoOfPiecesPerItem * ItemsPrice);

					FinalTotValPerItem = (TotValForCases + TotValForPieces)
							- ItemsDiscountValue;
					FinalTotValPerItem = Math.round(FinalTotValPerItem * 100) / 100.0d;
					String PrintTotValueForCases = Double
							.toString(FinalTotValPerItem);
					etdminvdtotitemsval.setText(PrintTotValueForCases);
				} else {
					TotValForCases = (ItemsCaseTotValue * NoOfCasesPerItem);
					FinalTotValPerItem = (TotValForCases - ItemsDiscountValue);
					String PrintTotValueForCases = Double
							.toString(FinalTotValPerItem);
					FinalTotValPerItem = Math.round(FinalTotValPerItem * 100) / 100.0d;
					etdminvdtotitemsval.setText(PrintTotValueForCases);
				}
			}
		}

		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {

			etdminvdtotitemsval.setText("");

			// do your stuff

		}

		public void onTextChanged(CharSequence s, int start, int before,
				int count) {

			if (etdminvdpiecesval.length() != 0) {
				String Item_Pieces = etdminvdpiecesval.getText().toString();
				NoOfPiecesPerItem = Double.parseDouble(Item_Pieces);

				TotValForPieces = (NoOfPiecesPerItem * ItemsPrice);
				FinalTotValPerItem = (TotValForPieces - ItemsDiscountValue);
				FinalTotValPerItem = Math.round(FinalTotValPerItem * 100) / 100.0d;
				String PrintTotValueForCases = Double
						.toString(FinalTotValPerItem);
				etdminvdtotitemsval.setText(PrintTotValueForCases);
			} else {
				etdminvdtotitemsval.setText("");
			}
			// do your stuff

		}

	};
	// ***********************************************************************************
	private TextWatcher filteretdminvdpiecesvalWatcher = new TextWatcher() {

		public void afterTextChanged(Editable s) {

			if (etdminvdpiecesval.length() != 0) {
				String Item_PerCase = etdminvdunitval.getText().toString();
				ItemsPerCase = Double.parseDouble(Item_PerCase);
				String Item_Price = etdminvdpriceval.getText().toString();
				ItemsPrice = Double.parseDouble(Item_Price);
				String Item_Pieces = etdminvdpiecesval.getText().toString();
				NoOfPiecesPerItem = Double.parseDouble(Item_Pieces);
				String Item_PriceUnits = etdminvdpricevalunit.getText()
						.toString();
				ItemsCaseTotValue = Double.parseDouble(Item_PriceUnits);
				// ItemsCaseTotValue = (ItemsPerCase * ItemsPrice);

				if (etdminvddiscountval.length() != 0) {
					String Item_Discounting = etdminvddiscountval.getText()
							.toString();
					ItemsDiscountValue = Double.parseDouble(Item_Discounting);
				} else {
					ItemsDiscountValue = 0.0;
				}

				if (NoOfPiecesPerItem >= ItemsPerCase) {
					Toast.makeText(getApplicationContext(),
							"Maximum Items Pieces:" + ItemsPerCase,
							Toast.LENGTH_SHORT).show();
					etdminvdpiecesval.setText("");
				} else {

					if (etdminvdcasesval.length() != 0) {
						/*
						 * Toast.makeText(getApplicationContext(), "BLOCK 01",
						 * Toast.LENGTH_SHORT).show();
						 */
						String Item_Cases = etdminvdcasesval.getText()
								.toString();
						NoOfCasesPerItem = Double.parseDouble(Item_Cases);

						TotValForCases = (ItemsCaseTotValue * NoOfCasesPerItem);
						TotValForPieces = (NoOfPiecesPerItem * ItemsPrice);

						FinalTotValPerItem = (TotValForCases + TotValForPieces)
								- ItemsDiscountValue;
						FinalTotValPerItem = Math
								.round(FinalTotValPerItem * 100) / 100.0d;
						String PrintTotValueForCases = Double
								.toString(FinalTotValPerItem);
						etdminvdtotitemsval.setText(PrintTotValueForCases);
					} else {
						/*
						 * Toast.makeText(getApplicationContext(), "BLOCK 02",
						 * Toast.LENGTH_SHORT).show();
						 */
						TotValForPieces = (NoOfPiecesPerItem * ItemsPrice);
						FinalTotValPerItem = (TotValForPieces - ItemsDiscountValue);
						FinalTotValPerItem = Math
								.round(FinalTotValPerItem * 100) / 100.0d;
						String PrintTotValueForCases = Double
								.toString(FinalTotValPerItem);
						etdminvdtotitemsval.setText(PrintTotValueForCases);
					}
				}
			}

		}

		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {

			etdminvdtotitemsval.setText("");

			// do your stuff

		}

		public void onTextChanged(CharSequence s, int start, int before,
				int count) {
			if (etdminvdcasesval.length() != 0) {
				/*
				 * Toast.makeText(getApplicationContext(), "BLOCK 03",
				 * Toast.LENGTH_SHORT).show();
				 */
				String Item_Cases = etdminvdcasesval.getText().toString();
				NoOfCasesPerItem = Double.parseDouble(Item_Cases);

				TotValForCases = (ItemsCaseTotValue * NoOfCasesPerItem);
				FinalTotValPerItem = TotValForCases - ItemsDiscountValue;
				FinalTotValPerItem = Math.round(FinalTotValPerItem * 100) / 100.0d;
				String PrintTotValueForCases = Double
						.toString(FinalTotValPerItem);
				etdminvdtotitemsval.setText(PrintTotValueForCases);
			} else {
				etdminvdtotitemsval.setText("");
			}
			// etdminvdtotitemsval.setText("44");

			// do your stuff

		}

	};
	// ***********************************************************************************
	private TextWatcher filteretdminvddiscountvalWatcher = new TextWatcher() {

		public void afterTextChanged(Editable s) {

			if (etdminvddiscountval.length() != 0) {
				String Item_Price = etdminvdpriceval.getText().toString();
				ItemsPrice = Double.parseDouble(Item_Price);
				String Item_PerCase = etdminvdunitval.getText().toString();
				ItemsPerCase = Double.parseDouble(Item_PerCase);
				if (etdminvdpiecesval.length() != 0
						&& etdminvdcasesval.length() != 0) {
					String Item_Discounting = etdminvddiscountval.getText()
							.toString();
					ItemsDiscountValue = Double.parseDouble(Item_Discounting);

					String Item_Pieces = etdminvdpiecesval.getText().toString();
					String Item_Cases = etdminvdcasesval.getText().toString();

					if (Item_Cases.length() != 0) {
						NoOfCasesPerItem = Double.parseDouble(Item_Cases);
						String Item_PriceUnits = etdminvdpricevalunit.getText()
								.toString();
						ItemsCaseTotValue = Double.parseDouble(Item_PriceUnits);
						// ItemsCaseTotValue = (ItemsPerCase * ItemsPrice);
					}
					if (Item_Pieces.length() != 0) {
						NoOfPiecesPerItem = Double.parseDouble(Item_Pieces);
					}
					TotValForCases = (ItemsCaseTotValue * NoOfCasesPerItem);
					TotValForPieces = (NoOfPiecesPerItem * ItemsPrice);
					double discountFinalTot = (TotValForCases + TotValForPieces)
							- ItemsDiscountValue;
					discountFinalTot = Math.round(discountFinalTot * 100) / 100.0d;
					String PrintTotValueForCases = Double
							.toString(discountFinalTot);
					etdminvdtotitemsval.setText(PrintTotValueForCases);
				} else {
					/*
					 * Toast.makeText(getApplicationContext(),
					 * "ELSE Bolock **********1:", Toast.LENGTH_SHORT) .show();
					 */
					if (etdminvdpiecesval.length() != 0
							&& etdminvdcasesval.length() == 0) {
						String Item_Discounting = etdminvddiscountval.getText()
								.toString();
						ItemsDiscountValue = Double
								.parseDouble(Item_Discounting);
						String Item_Pieces = etdminvdpiecesval.getText()
								.toString();
						NoOfPiecesPerItem = Double.parseDouble(Item_Pieces);
						TotValForPieces = (NoOfPiecesPerItem * ItemsPrice);
						double discountFinalTot = (TotValForPieces - ItemsDiscountValue);
						discountFinalTot = Math.round(discountFinalTot * 100) / 100.0d;
						String PrintTotValueForCases = Double
								.toString(discountFinalTot);
						/*
						 * Toast.makeText( getApplicationContext(),
						 * "ELSE Bolock **********1 :if" +
						 * PrintTotValueForCases, Toast.LENGTH_SHORT).show();
						 */
						etdminvdtotitemsval.setText(PrintTotValueForCases);
					} else {

						String Item_Cases = etdminvdcasesval.getText()
								.toString();
						String Item_Discounting = etdminvddiscountval.getText()
								.toString();
						ItemsDiscountValue = Double
								.parseDouble(Item_Discounting);
						if (Item_Cases.length() != 0) {
							NoOfCasesPerItem = Double.parseDouble(Item_Cases);
						}
						String Item_PriceUnits = etdminvdpricevalunit.getText()
								.toString();
						ItemsCaseTotValue = Double.parseDouble(Item_PriceUnits);
						// ItemsCaseTotValue = (ItemsPerCase * ItemsPrice);
						TotValForCases = (ItemsCaseTotValue * NoOfCasesPerItem);
						double discountFinalTot = (TotValForCases - ItemsDiscountValue);
						discountFinalTot = Math.round(discountFinalTot * 100) / 100.0d;
						String PrintTotValueForCases = Double
								.toString(discountFinalTot);
						/*
						 * Toast.makeText( getApplicationContext(),
						 * "ELSE Bolock **********1 :Else" +
						 * PrintTotValueForCases, Toast.LENGTH_SHORT).show();
						 */
						etdminvdtotitemsval.setText(PrintTotValueForCases);
					}
				}
			}

		}

		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
			/*
			 * Toast.makeText(getApplicationContext(), "Bolock **********2:",
			 * Toast.LENGTH_SHORT).show();
			 */
			ItemsDiscountValue = 0.0;

			// do your stuff

		}

		public void onTextChanged(CharSequence s, int start, int before,
				int count) {

			if (etdminvddiscountval.length() == 0) {
				if (etdminvdpiecesval.length() != 0
						&& etdminvdcasesval.length() != 0) {
					/*
					 * String Item_Discounting = etdminvddiscountval.getText()
					 * .toString(); ItemsDiscountValue =
					 * Double.parseDouble(Item_Discounting);
					 */
					String Item_Price = etdminvdpriceval.getText().toString();
					ItemsPrice = Double.parseDouble(Item_Price);
					String Item_Pieces = etdminvdpiecesval.getText().toString();
					String Item_Cases = etdminvdcasesval.getText().toString();

					String Item_PerCase = etdminvdunitval.getText().toString();
					ItemsPerCase = Double.parseDouble(Item_PerCase);
					if (Item_Cases.length() != 0) {
						NoOfCasesPerItem = Double.parseDouble(Item_Cases);
						String Item_PriceUnits = etdminvdpricevalunit.getText()
								.toString();
						ItemsCaseTotValue = Double.parseDouble(Item_PriceUnits);
						// ItemsCaseTotValue = (ItemsPerCase * ItemsPrice);
					}
					if (Item_Pieces.length() != 0) {
						NoOfPiecesPerItem = Double.parseDouble(Item_Pieces);
					}
					TotValForCases = (ItemsCaseTotValue * NoOfCasesPerItem);
					TotValForPieces = (NoOfPiecesPerItem * ItemsPrice);
					FinalTotValPerItem = (TotValForCases + TotValForPieces);
					FinalTotValPerItem = Math.round(FinalTotValPerItem * 100) / 100.0d;
					String PrintTotValueForCases = Double
							.toString(FinalTotValPerItem);
					etdminvdtotitemsval.setText(PrintTotValueForCases);
				} else {
					/*
					 * Toast.makeText(getApplicationContext(),
					 * "ELSE Bolock **********1:", Toast.LENGTH_SHORT) .show();
					 */
					if (etdminvdpiecesval.length() != 0
							&& etdminvdcasesval.length() == 0) {

						String Item_Pieces = etdminvdpiecesval.getText()
								.toString();
						NoOfPiecesPerItem = Double.parseDouble(Item_Pieces);
						TotValForPieces = (NoOfPiecesPerItem * ItemsPrice);
						TotValForPieces = Math.round(TotValForPieces * 100) / 100.0d;
						String PrintTotValueForCases = Double
								.toString(TotValForPieces);
						/*
						 * Toast.makeText( getApplicationContext(),
						 * "ELSE Bolock **********1 :if" +
						 * PrintTotValueForCases, Toast.LENGTH_SHORT).show();
						 */
						etdminvdtotitemsval.setText(PrintTotValueForCases);
					} else {

						String Item_Cases = etdminvdcasesval.getText()
								.toString();
						if (Item_Cases.length() != 0) {
							NoOfCasesPerItem = Double.parseDouble(Item_Cases);
						}
						String Item_PriceUnits = etdminvdpricevalunit.getText()
								.toString();
						if (Item_PriceUnits.length() != 0) {
							ItemsCaseTotValue = Double
									.parseDouble(Item_PriceUnits);
						}

						// ItemsCaseTotValue = (ItemsPerCase * ItemsPrice);
						TotValForCases = (ItemsCaseTotValue * NoOfCasesPerItem);
						TotValForCases = Math.round(TotValForCases * 100) / 100.0d;
						String PrintTotValueForCases = Double
								.toString(TotValForCases);
						/*
						 * Toast.makeTextToast.makeText(
						 * getApplicationContext(),
						 * "ELSE Bolock **********1 :Else" +
						 * PrintTotValueForCases, Toast.LENGTH_SHORT).show();
						 */
						etdminvdtotitemsval.setText(PrintTotValueForCases);
					}
				}
			}

		}

	};
}
